package com.huli.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huli.domain.SysUser;
import com.huli.service.SysUserService;
import com.huli.mapper.SysUserMapper;
import com.huli.util.CaptchaUtil;
import com.huli.util.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.Map;

/**
* @author 张庆阳
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2025-03-11 18:17:58
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService{
@Autowired
private RedisClient redisClient;
@Autowired
private SysUserMapper sysUserMapper;
    @Override
    public boolean login(String phone, int captcha) throws Exception {
        //检查手机号是否存在
        String phone1 = sysUserMapper.getPhone(phone);
        System.err.println(phone);
        if (!phone1.equals(phone)){
            throw  new Exception("手机号不存在");
        }
        //构造redis中的验证码键
        String redisKey="verifyCode:"+phone;
        //从redis中获取验证码
        Object redisCode = redisClient.get(redisKey);
        if (redisCode==null){
            throw new Exception("验证码已过期或不存在");
        }
        //登录
        boolean login = sysUserMapper.login(phone, captcha);
        if (!login){
            throw new Exception("手机号或验证码错误");
        }
        //验证码比对
        if (redisCode.equals(captcha)){
            //验证成功删除验证码
            redisClient.del(redisKey);
            return true;
        }else {
            //验证失败，不删除验证码
            return false;
        }
    }

    @Override
    public void creteCaptcha(String phone) throws Exception {
        // 检查手机号是否存在，如果不存在则创建新用户
        String existingPhone = sysUserMapper.getPhone(phone);
        if (existingPhone == null || existingPhone.isEmpty()) {
            // 创建新用户
            SysUser user = new SysUser();
            user.setPhone(phone);
            user.setUsername(phone);  // 默认使用手机号作为用户名
            user.setStatus(0);        // 设置用户状态为启用
            user.setCreateTime(new Date());  // 设置创建时间
            // 保存用户到数据库
            save(user);
        }
        // 构造Redis中的验证码键
        String redisKey = "verifyCode:" + phone;
        // 检查Redis中是否已经存在验证码
        String existingCode = (String) redisClient.get(redisKey);
        if (existingCode != null) {
            // 验证码已存在且未过期，拒绝再次发送
            throw new Exception("验证码已发送，请稍后再试！");
        }
        // 生成6位随机数
        String captcha;
        do {
            captcha = CaptchaUtil.generateCaptcha(6);
        } while (captcha.charAt(0) == '0');
        // 添加到redis
        redisClient.set(redisKey, captcha);
        // 修改mysql里的数据
        sysUserMapper.insertCaptcha(phone, Integer.parseInt(captcha));
    }
}




